package com.imooc.service.impl.center;

import com.imooc.enums.ErrorMsg;
import com.imooc.exception.CustomException;
import com.imooc.mapper.UsersMapper;
import com.imooc.pojo.Users;
import com.imooc.pojo.bo.center.UserCenterBO;
import com.imooc.service.center.UserCenterService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @author 逸尘风清
 * @date 2021/5/11
 * @time 9:04
 * 描述：
 */
@Service
public class UserCenterServiceImpl implements UserCenterService {
    @Resource
    private UsersMapper usersMapper;

    @Override
    public Users queryUserInfoById(String userId){
        Users user = usersMapper.selectByPrimaryKey(userId);
        if (user == null) {
            throw new CustomException(ErrorMsg.USER_NOT_EXIST);
        }
        user.setPassword("");
        return user;
    }

    @Override
    public Users updateUserInfo(String userId, UserCenterBO userCenterBO){
        Users res = usersMapper.selectByPrimaryKey(userId);
        Users updateUser = new Users();
        BeanUtils.copyProperties(userCenterBO,updateUser);
        updateUser.setId(userId);
        updateUser.setCreatedTime(new Date());
        // 防止用户传了密码却没有被加密，故重新获取之前的密码来覆盖
        updateUser.setPassword(res.getPassword());
        usersMapper.updateByPrimaryKeySelective(updateUser);
        return queryUserInfoById(userId);
    }

    @Override
    public Users updateFaceUrl(String userId, String faceUrl) {
        Users user = usersMapper.selectByPrimaryKey(userId);
        user.setFace(faceUrl);
        usersMapper.updateByPrimaryKeySelective(user);
        return queryUserInfoById(userId);
    }
}
